﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Json;
using System.Net.NetworkInformation;
using System.Reflection;

namespace JsonViewer
{
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();

            this.btnViewJsonTree.Click += new RoutedEventHandler(btnViewJsonTree_Click);
            this.tvJsonTree.SelectedItemChanged += new RoutedPropertyChangedEventHandler<object>(tvJsonTree_SelectedItemChanged);

            this.UpdateInstallButtonVisual();
            Application.Current.InstallStateChanged += new EventHandler(Current_InstallStateChanged);
            this.btnInstall.Click += new RoutedEventHandler(btnInstall_Click);

            Application.Current.CheckAndDownloadUpdateAsync();

            if (Application.Current.IsRunningOutOfBrowser && NetworkInterface.GetIsNetworkAvailable())
            {
                Application.Current.CheckAndDownloadUpdateCompleted += new CheckAndDownloadUpdateCompletedEventHandler(Current_CheckAndDownloadUpdateCompleted);
                Application.Current.CheckAndDownloadUpdateAsync();
            }

            object[] atts = this.GetType().Assembly.GetCustomAttributes(typeof(AssemblyFileVersionAttribute), false);
            AssemblyFileVersionAttribute att = atts[0] as AssemblyFileVersionAttribute;

            if (att != null)
            {
                this.txtVersionInfo.Text = string.Format("版本:{0}", att.Version);
            }
        }

        void Current_CheckAndDownloadUpdateCompleted(object sender, CheckAndDownloadUpdateCompletedEventArgs e)
        {
            if (e.UpdateAvailable)
            {
                MessageBox.Show("程序已更新到最新版本，请重新启动!", "系统提示", MessageBoxButton.OK);
            }
            else
            {
                if (e.Error != null)
                {
                    MessageBox.Show("程序更新失败，错误信息如下：" + Environment.NewLine + e.Error.Message, "系统提示", MessageBoxButton.OK);
                }
            }
        }

        void btnInstall_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                Application.Current.Install();
            }
            catch { }
        }

        void Current_InstallStateChanged(object sender, EventArgs e)
        {
            this.UpdateInstallButtonVisual();
        }

        private void UpdateInstallButtonVisual()
        {
            if (Application.Current.InstallState == InstallState.NotInstalled)
            {
                this.btnInstall.IsEnabled = true;
            }
            else
            {
                this.btnInstall.IsEnabled = false;
            }
        }

        void tvJsonTree_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            JsonNode jsonNode = this.tvJsonTree.SelectedItem as JsonNode;
            if (jsonNode != null)
            {
                this.txtPropertyJson.Text = string.Format("{0}", jsonNode.PropertyValue);
                this.dgPropertys.ItemsSource = this.GetPropertyData(jsonNode.PropertyName, jsonNode.PropertyValue);
            }
            else
            {
                this.dgPropertys.ItemsSource = null;
                this.txtPropertyJson.Text = string.Empty;
            }
        }

        void btnViewJsonTree_Click(object sender, RoutedEventArgs e)
        {
            JsonValue value = null;
            try
            {
                value = JsonObject.Parse(this.txtSrcJson.Text);
            }
            catch (Exception)
            {
            }

            JsonNode root = new JsonNode()
            {
                PropertyName = "Json",
                PropertyValue = value
            };

            this.DataContext = new JsonNode[] { root };
        }

        private List<JsonKeyValue> GetPropertyData(string propertyName, JsonValue jsonValue)
        {
            List<JsonKeyValue> lst = new List<JsonKeyValue>();

            if (jsonValue == null)
            {
                lst.Add(new JsonKeyValue()
                {
                    Key = propertyName,
                    Value = "null"
                });

                return lst;
            }

            if (jsonValue.JsonType == JsonType.Number || jsonValue.JsonType == JsonType.Boolean || jsonValue.JsonType == JsonType.String)
            {
                lst.Add(new JsonKeyValue()
                {
                    Key = propertyName,
                    Value = string.Format("{0}", jsonValue)
                });
            }
            else if (jsonValue.JsonType == JsonType.Array)
            {
                int index = 0;
                foreach (JsonValue item in jsonValue)
                {
                    lst.Add(new JsonKeyValue()
                    {
                        Key = index.ToString(),
                        Value = string.Format("{0}", item)
                    });

                    index++;
                }
            }
            else if (jsonValue.JsonType == JsonType.Object)
            {
                foreach (KeyValuePair<string, JsonValue> keyValue in jsonValue)
                {
                    lst.Add(new JsonKeyValue()
                    {
                        Key = keyValue.Key,
                        Value = string.Format("{0}", keyValue.Value)
                    });
                }
            }

            return lst;
        }
    }
}
